package com.lovesher.payment.service.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.lovesher.payment.common.service.ResubmitService;

@Service("resubmitService")
public class ResubmitServiceImpl implements ResubmitService {

	@Autowired
	RedisTemplate<Object, Object> redisTemplate;

	@Override
	public Boolean isReSubmitForCommon(String key, String paramKey, String methodName,
			Integer redisExpire) {
		String redisKey = new StringBuffer(key).append("_").append(methodName).append("_").append(paramKey).toString();
		return (Boolean) redisTemplate.execute(new RedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
				RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
				byte[] key = redisSerializer.serialize(redisKey);
				byte[] value = redisSerializer.serialize("1");
				boolean b = connection.setNX(key, value);//存入为true
				if (b) {
					connection.setEx(key, redisExpire, value);
				}
				return !b;
			}
		});
	}
}
